<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>webgl平移_07</title>
  <script src="lib/webgl-debug.js"></script>
  <script src="lib/webgl-utils.js"></script>
  <script src="lib/cuon-utils.js"></script>
  <script src="lib/cuon-matrix.js"></script>
</head>

<body onload="main()">
  <canvas id="canvas" width="400" height="490"></canvas>
</body>
<script>
  // 顶点着色器伪代码
  var vShder_source = `
attribute  vec4 a_Position;
uniform  vec4 u_Translation;
void main(){
  gl_Position  =a_Position+u_Translation; //设置坐标
}
`
  //片元着色器伪代码
  var fShder_source = `
  precision mediump float ;
uniform vec4 u_FragColor ;
void main(){
  gl_FragColor =u_FragColor ; //设置颜色
}
`

  var tx = 0.3, ty = 0.3, tz = 0;

  function main() {
    var canvas = document.getElementById('canvas');
    //  获取上下文对象
    var gl = getWebGLContext(canvas);
    //  初始化着色器
    if (!initShaders(gl, vShder_source, fShder_source)) {
      console.log("着色器失败")
      return;
    }

    var n = initVertexBuffers(gl);

    // 指定一个覆盖canvas的颜色
    gl.clearColor(0, 0, 0, 1.0);
    var u_FragColor = gl.getUniformLocation(gl.program, "u_FragColor");
    gl.uniform4f(u_FragColor, 1, 0.5, 0, 1);
    var u_Translation =gl.getUniformLocation(gl.program,"u_Translation");
    gl.uniform4f(u_Translation,0.5,0.0,0.0,0.0)
    // 清除指定的缓冲区
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLE_FAN, 0, n);
  
  }

  function initVertexBuffers(gl) {
    var verties = new Float32Array([-0.5, 0.5, - 0.5, -0.5, 0.5, -0.5, 0.5, 0.5]);
    var n = 4;
    //创建缓冲区
    var vertexBuffer = gl.createBuffer();
    if (!vertexBuffer) {
      console.log("创建缓冲区失败");
      return;
    }
    //将缓冲区对象绑定到目标
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    //向缓冲区写入数据
    gl.bufferData(gl.ARRAY_BUFFER, verties, gl.STATIC_DRAW);
    //获取 attribute 变量的储存位置
    var a_Position = gl.getAttribLocation(gl.program, "a_Position");
    //将缓冲区对象分配给 a_Position对象
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(a_Position);
    return n
  }
</script>

</html>